package com.sangeng.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sangeng.domain.entity.role.Permission;
import com.sangeng.domain.vo.PermissionTreeVO;
import com.sangeng.mapper.PermissionMapper;
import com.sangeng.service.IPermissionService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {
    
    /**
     * 查询权限树
     * @return 权限树列表
     */
    @Override
    public List<PermissionTreeVO> getPermissionTree() {
        // 1. 查询所有启用的权限，按排序号排序
        List<Permission> allPermissions = lambdaQuery()
                .eq(Permission::getStatus, 0) // 0-启用
                .orderByAsc(Permission::getSortOrder)
                .orderByAsc(Permission::getId)
                .list();
        
        // 2. 转换为VO对象并建立ID映射
        Map<Long, PermissionTreeVO> permissionMap = allPermissions.stream()
                .collect(Collectors.toMap(
                    Permission::getId,
                    this::convertToVO,
                    (existing, replacement) -> existing
                ));
        
        // 3. 构建父子关系 - 把每个权限放入其父节点的孩子中
        List<PermissionTreeVO> rootNodes = new ArrayList<>();
        
        for (PermissionTreeVO permission : permissionMap.values()) {
            if (permission.getParentId() == 0) {
                // 根节点
                rootNodes.add(permission);
            } else {
                // 子节点 - 找到父节点并添加到其children中
                PermissionTreeVO parent = permissionMap.get(permission.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(permission);
                }
            }
        }
        
        return rootNodes;
    }
    
    /**
     * Permission转换为PermissionTreeVO
     */
    private PermissionTreeVO convertToVO(Permission permission) {
        PermissionTreeVO vo = new PermissionTreeVO();
        BeanUtil.copyProperties(permission, vo);
        
        // 权限类型转换为字符串
        if (permission.getPermissionType() != null) {
            vo.setType(permission.getPermissionType() == 1 ? "menu" : "button" );
        }
        
        return vo;
    }
}
